import React from 'react';
import axios from 'axios';
import {Button, Form, DatePicker, Card, Input, Popconfirm, message, Divider, Row, Col, Select} from 'antd';
import Grid from '../../components/table/grid';
import BindStaff from './bindStaff'
import { injectIntl } from 'react-intl';

const RangePicker = DatePicker.RangePicker;
const FormItem = Form.Item;
const Option = Select.Option;

@Form.create()
class CardList extends React.Component {

    constructor(Props) {
        super(Props);
        this.state = {
            selectUrl: '/report/departMent',
        };
        const common = this.props.intl.messages.common;
        this.columns = [{
            title: common.electricCardNO,
            dataIndex: 'no',
            width: '20%'
        }, {
            title: common.status,
            dataIndex: 'statusCopy',
            width: '20%',
            render: (text, record) => (
                <span>
                    {this.getStatus(record.status)}
                </span>
            )
        }, {
            title: common.username,
            dataIndex: 'account',
            width: '20%'
        }, {
            title: common.staffName,
            dataIndex: 'name',
            width: '20%'
        }, {
            title: common.operation,
            width: '20%',
            key: 'action',
            render: (text, record) => (
                this.getToolLink(record.status, record.accountId, record.id, record.no)
            )
        }],
            this.state = {
                params: {
                    name: '',
                    account: '',
                    no: '',
                    status: '',
                },
                refresh: 0,
                bindStaff: false,
                cardId: ''
            };
    }

    getStatus = (status) => {
        const common = this.props.intl.messages.common;
        return status == 2 ? <span style={{color: "red"}}>{common.disabled}</span> : common.enabled;
    }


    unBindCard(values) {
        axios.post('api/user/card/unbind', {
            ...values
        }).then(res => {
            if(res&&res.code==200){
                this.setState({
                    refresh: this.state.refresh + 1
                });
            }
        });
    }

    getToolLink = (status, accountId, id) => {
        const common = this.props.intl.messages.common;
        if (status == 2) {
            return (
                <div><Popconfirm title={`${common.needToEnableIt}？`} okText={common.sure} onConfirm={() => this.modStatus({'id': id, 'status': 1})}
                                 cancelText={common.cancel}>
                    <a>{common.enabled}</a>
                </Popconfirm></div>)
        } else if (status == 1 && accountId != undefined && accountId != '' && accountId != null) {
            return (
                <div>
                    <Popconfirm title={`${common.needToCancelBinding}?`} okText={common.sure} onConfirm={() => this.unBindCard({'id': id})}
                                cancelText={common.cancel}>
                        <a>{common.cancelBind}</a>
                    </Popconfirm> |
                    <Popconfirm title={`${common.needToDisableIt}？`} okText={common.sure} onConfirm={() => this.modStatus({'id': id, 'status': 2})}
                                cancelText={common.cancel}>
                        <a>{common.disabled}</a>
                    </Popconfirm>
                </div>);
        } else if (status == 1 && (accountId == undefined || accountId == '' || accountId == null)) {
            return (
                <div>
                    <a onClick={() => this.showModalX('bindStaff', true, id)}>{common.bindStaff}</a> |
                    <Popconfirm title={`${common.needToDisableIt}?`} okText={common.sure} onConfirm={() => this.modStatus({'id': id, 'status': 2})}
                                cancelText={common.cancel}>
                        <a>{common.disabled}</a>
                    </Popconfirm>
                </div>);
        }
    }

    /*
     *星卡启用和禁用
    */
    modStatus = (values) => {
        axios.post('api/user/card/mod', {
            ...values
        }).then(res => {
            if(res&&res.code==200){
                this.setState({
                    refresh: this.state.refresh + 1
                });
            }
        });
    }

    /**
     * 输入框变更修改state内容
     * @param {*} type
     * @param {*} event
     */
    handleChange(type, event) {
        if (type == 'account') {
            this.setState(Object.assign(this.state.params, {account: event.target.value}));
        } else if (type == 'name') {
            this.setState(Object.assign(this.state.params, {name: event.target.value}));
        } else if (type == 'no') {
            this.setState(Object.assign(this.state.params, {no: event.target.value}));
        } else if (type == 'status') {
            this.setState(Object.assign(this.state.params, {status: event}));
        }
    }

    /**
     * 查询后变更表格内容
     */
    search = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                return;
            }
            console.log(values);
            this.setState({
                params: {...values},
                refresh: this.state.refresh + 1
            });
        });
    }

    handleReset = () => {
        this.props.form.resetFields();
    }

    /**
     * 初始化模态窗口信息
     * @param {*} key
     * @param {*} value
     * @param {*} cardId
     */
    showModalX(key, value, cardId) {
        this.setState({
            [key]: value,
            cardId: cardId
        })
    }

    /**
     * 模态窗体绑卡后的刷新
     * @param {*} key
     * @param {*} value
     * @param {*} isRefresh
     */
    showModal(key, value, isRefresh) {
        let count = 0;
        if (isRefresh) {
            count += 1;
        }
        this.setState({
            [key]: value,
            refresh: this.state.refresh + 1
        })
    }

    /**
     * 重置表单
     */
    resetForm() {
        document.getElementById('name').value = '';
        document.getElementById('account').value = '';
        document.getElementById('no').value = '';
        document.getElementsByClassName('ant-select-selection__placeholder')[0].setAttribute('style', 'display: block;user-select: none;');
        document.getElementsByClassName('ant-select-selection-selected-value')[0].setAttribute('style', 'display: none;user-select: none;');
        this.setState(Object.assign(this.state.params, {
            name: '',
            account: '',
            no: '',
            status: '',
        }))
        console.log(this.state.params)
    }

    render() {
        const gridStyle = {
            width: '50%',
            textAlign: 'center',
            marginBottom: '20px',
            display: 'inline-block'
        };

        const formItemLayout = {
            labelCol: {
                span: 0
            },
            wrapperCol: {
                span: 24
            },
        }
        const {getFieldDecorator} = this.props.form;
        // const token = JSON.parse(sessionStorage.getItem("token")).token;
        const token=JSON.parse(sessionStorage.getItem("token")||{}).token;
        const locale=JSON.parse(sessionStorage.getItem("locale")).saveValue;

        const common = this.props.intl.messages.common;

        return (
            <div>
                <form form={this.props.form}>
                    <Row gutter={16}>
                        <Col span={3}>
                            <FormItem {...formItemLayout} >
                                {getFieldDecorator('account', {})(<Input id="account" placeholder={common.username}/>)}
                            </FormItem>
                        </Col>
                        <Col span={3}>
                            <FormItem {...formItemLayout} >
                                {getFieldDecorator('name', {})(<Input id="name" placeholder={common.staffName}/>)}
                            </FormItem>
                        </Col>
                        <Col span={3}>
                            <FormItem {...formItemLayout} >
                                {getFieldDecorator('no', {})(<Input id="no" placeholder={common.electricCardNO}/>)}
                            </FormItem>
                        </Col>
                        <Col span={3}>
                            <FormItem {...formItemLayout} >
                                {getFieldDecorator('status', {})(<Select placeholder={common.status}>
                                    <Option value=''>{common.all}</Option>
                                    <Option value='1'>{common.enabled}</Option>
                                    <Option value='2'>{common.disabled}</Option>
                                </Select>)}
                            </FormItem>
                        </Col>
                        <Col span={9}>
                            <FormItem>
                                <Button className="ant-btn-84" onClick={this.handleReset}>{common.clear}</Button>
                                <Button type="primary" className="ant-btn-84"
                                        onClick={this.search}>{common.search}</Button>
                                <a href={`${axios.defaults.baseURL}/api/user/card/export?name=${this.state.params.name?this.state.params.name:''}&no=${this.state.params.no?this.state.params.no:''}&account=${this.state.params.account?this.state.params.account:''}&token=${token}&locale=${locale}`}>
                                    <Button type="primary" className="ant-btn-84">{common.exportStatement}</Button>
                                </a>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <Grid refresh={this.state.refresh} params={this.state.params} columns={this.columns}
                      url="/api/user/card/qry"/>
                <BindStaff visible={this.state.bindStaff} cardId={this.state.cardId}
                           close={isRefresh => this.showModal('bindStaff', false, isRefresh)}/>
            </div>
        );
    }
}

export default injectIntl(CardList);